package com.mas.framework.datasource.config;

import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.mas.framework.datasource.core.filter.DruidAdRemoveFilter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Optional;

/**
 * @author godyao
 * @description 数据库配置类
 * @date 2023年01月18日20:48
 */
@AutoConfiguration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableConfigurationProperties(DruidStatProperties.class)
public class MasDatasourceAutoConfiguration {

    /**
     * 注册 <druid 底部广告去除过滤器>
     *
     * @param properties 属性配置
     * @return org.springframework.boot.web.servlet.FilterRegistrationBean<javax.servlet.Filter>
     * @author godyao
     * @date 2023/1/18 20:55
     */
    @Bean
    public FilterRegistrationBean<DruidAdRemoveFilter> druidAdRemoveFilterFilter(DruidStatProperties properties) {
        // 获取 druid web 监控页面的参数
        final DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取 common.js 的配置路径
        final String pattern = Optional.ofNullable(config.getUrlPattern()).orElse("/druid/*");
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        // 创建 DruidAdRemoveFilter Bean
        final FilterRegistrationBean<DruidAdRemoveFilter> druidAdRemoveFilterFilterRegistrationBean = new FilterRegistrationBean<>();
        druidAdRemoveFilterFilterRegistrationBean.setFilter(new DruidAdRemoveFilter());
        druidAdRemoveFilterFilterRegistrationBean.addUrlPatterns(commonJsPattern);
        return druidAdRemoveFilterFilterRegistrationBean;
    }

}
